package com.hgyc.mom.generator.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hgyc.mom.common.util.DateUtils;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.generator.constant.GenConstants;
import com.hgyc.mom.generator.entity.GenColumnDictInfoVO;
import com.hgyc.mom.generator.entity.GenTable;
import com.hgyc.mom.generator.entity.GenTableColumn;
import com.hgyc.mom.generator.entity.GenTableInfoVO;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 模板处理工具类
 * 
 * @author fwj
 */
public class TemplateUtils
{
    /** 项目空间路径 */
    private static final String PROJECT_PATH = "main/java";

    /** mybatis空间路径 */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /** 默认上级菜单，根目录 */
    private static final String DEFAULT_PARENT_MENU_ID = "0";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static Map<String, Object> prepareContext(GenTableInfoVO genTable) throws JsonProcessingException {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String packageName = genTable.getPackageName();
        String tplCategory = genTable.getTplCategory();
        String functionName = genTable.getFunctionName();

        Map<String, Object> context = new LinkedHashMap<>();
        context.put("tplCategory", tplCategory);
        context.put("tableName", genTable.getTableName());
        context.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        context.put("ClassName", genTable.getClassName());
        context.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        context.put("moduleName", moduleName);
        context.put("BusinessName", StringUtils.capitalize(businessName));
        context.put("businessName", businessName);
        context.put("basePackage", getPackagePrefix(packageName));
        context.put("packageName", packageName);
        context.put("author", genTable.getFunctionAuthor());
        context.put("datetime", DateUtils.getDate());
        context.put("importList", getImportList(genTable));
        context.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        context.put("table", genTable);
        context.put("columns", genTable.getColumns());
        context.put("dicts", getDicts(genTable));
        context.put("parentMenuId", genTable.getParentMenuId()==null ? DEFAULT_PARENT_MENU_ID : genTable.getParentMenuId());

        //子表信息
        if (!CollectionUtils.isEmpty(genTable.getChildrenTable())) {
            List<Map<String, Object>> childrenContext = new ArrayList<>();
            List<GenTableInfoVO> childrenTable = genTable.getChildrenTable();
            for (GenTableInfoVO child : childrenTable) {
                Map<String, Object> map = prepareContext(child);
                childrenContext.add(map);
            }
            context.put("childrenTables", childrenContext);
        }

        if (GenConstants.TPL_TREE.equals(tplCategory)) {
            setTreeContext(context, genTable);
        }
        if (GenConstants.TPL_CHILDREN.equals(tplCategory)) {
            setSubContext(context, genTable);
        }
        return context;
    }

    private static void setTreeContext(Map<String, Object> context, GenTableInfoVO genTable) {
        context.put("treeCode", genTable.getTreeCode());
        context.put("treeParentCode", genTable.getTreeParentCode());
        context.put("treeName", genTable.getTreeName());
    }

    private static void setSubContext(Map<String, Object> context, GenTableInfoVO genTable) {
        context.put("parentId", StringUtils.uncapitalize(StringUtils.convertToCamelCase(genTable.getSubTableFkName())));
        context.put("ParentId", StringUtils.capitalize(StringUtils.convertToCamelCase(genTable.getSubTableFkName())));
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory)
    {
        List<String> templates = new ArrayList<>();
        templates.add("java/entity.java.ftl");
        templates.add("java/param.java.ftl");
        if (GenConstants.TPL_PARENT.equals(tplCategory)) {
            templates.add("java/vo.java.ftl");
        }
        templates.add("java/service.java.ftl");
        templates.add("java/mapper.java.ftl");
        templates.add("java/serviceImpl.java.ftl");
        templates.add("java/controller.java.ftl");
        templates.add("xml/mapper.xml.ftl");
        templates.add("js/entity.d.ts.ftl");

        if (GenConstants.TPL_CHILDREN.equals(tplCategory))
        {
            templates.add("react/children.tsx.ftl");
        } else {
            templates.add("sql/sql.ftl");
            templates.add("js/api.ts.ftl");
            templates.add("react/index.tsx.ftl");
        }
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable)
    {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = genTable.getBusinessName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + moduleName;
        String reactPath = "react";

        if (template.contains("entity.java.ftl"))
        {
            fileName = StringUtils.format("{}/api/entity/{}.java", javaPath, className);
        }
        if (template.contains("param.java.ftl"))
        {
            fileName = StringUtils.format("{}/api/vo/{}Param.java", javaPath, className);
        }
        if (template.contains("js/vo.java.ftl"))
        {
            fileName = StringUtils.format("{}/api/vo/{}VO.java", javaPath, className);
        }
        else if (template.contains("mapper.java.ftl"))
        {
            fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
        }
        else if (template.contains("service.java.ftl"))
        {
            fileName = StringUtils.format("{}/api/service/{}Service.java", javaPath, className);
        }
        else if (template.contains("serviceImpl.java.ftl"))
        {
            fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
        }
        else if (template.contains("controller.java.ftl"))
        {
            fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
        }
        else if (template.contains("mapper.xml.ftl"))
        {
            fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
        }
        else if (template.contains("sql.ftl"))
        {
            fileName = businessName + "Menu.sql";
        }
        else if (template.contains("api.ts.ftl"))
        {
            fileName = StringUtils.format("{}/service/{}/{}.ts", reactPath , moduleName, businessName);
        }
        else if (template.contains("entity.d.ts.ftl"))
        {
            fileName = StringUtils.format("{}/pages/{}/{}/entity.d.ts", reactPath , moduleName, businessName);
        }
        else if (template.contains("index.tsx.ftl"))
        {
            fileName = StringUtils.format("{}/pages/{}/{}/index.tsx", reactPath , moduleName, businessName);
        }
        else if (template.contains("children.tsx.ftl"))
        {
            fileName = StringUtils.format("{}/pages/{}/{}/{}.tsx", reactPath , moduleName, businessName);
        }
        return fileName;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName)
    {
        int lastIndex = packageName.lastIndexOf(".");
        return StringUtils.substring(packageName, 0, lastIndex);
    }

    /**
     * 根据列类型获取导入包
     * 
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTableInfoVO genTable)
    {
        List<GenTableColumn> columns = genTable.getColumns();
        GenTable subGenTable = genTable.getParentTable();
        HashSet<String> importList = new HashSet<>();
        if (StringUtils.isNotNull(subGenTable))
        {
            importList.add("java.util.List");
        }
        for (GenTableColumn column : columns)
        {
            if (GenConstants.TYPE_DATE_TIME.equals(column.getJavaType()))
            {
                importList.add("java.time.LocalDateTime");
            } else if (GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.time.LocalDate");
            }
            else if (GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType()))
            {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 根据列类型获取字典组
     * 
     * @param genTable 业务表对象
     * @return 返回字典组
     */
    public static List<GenColumnDictInfoVO> getDicts(GenTableInfoVO genTable)
    {
        List<GenTableColumn> columns = genTable.getColumns();
        Set<String> dicts = new HashSet<>();
        List<GenColumnDictInfoVO> dictInfos = new ArrayList<>();

        for (GenTableColumn column : columns) {
            if (StringUtils.isNotEmpty(column.getDictType())
                    && StringUtils.equalsAny(
                    column.getHtmlType(),
                    new String[] { GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX })) {
                String dictType = column.getDictType();
                if (!dicts.contains(dictType)) {
                    dicts.add(dictType);

                    GenColumnDictInfoVO dictInfo = new GenColumnDictInfoVO();
                    dictInfo.setDictCode(dictType);
                    dictInfo.setFieldName(column.getJavaField());

                    dictInfos.add(dictInfo);
                }
            }
        }
        return dictInfos;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName 模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName)
    {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

}
